package com.douyang.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.douyang.base.enumeration.OrderStatementStatusEnum;
import com.douyang.model.OrderStatement;
import com.douyang.model.OrderStatementLog;
import com.douyang.service.OrderStatementLogService;
import com.douyang.service.SaveLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service("updateOrderStatementState")
public class SaveUpdateOrderStatementStateServiceImpl implements SaveLogService {

    @Autowired
    OrderStatementLogService orderStatementLogService;


    private String getStateNameByState(int i){
        return switch (i) {
            case 0 -> "等待支付";
            case 1 -> "支付成功";
            case 2 -> "已取消";
            case 3 -> "退款中";
            case 4 -> "退款成功";
            case 5 -> "超时";
            case 6 -> "失败";
            case 7 -> "未知";
            default -> "";
        };
    }



    @Override
    public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Object[] args = joinPoint.getArgs();
        OrderStatement orderStatement = (OrderStatement) args[0];
        int state= (int) args[1];
        String failReason= (String) args[2];
        Double price= (Double) args[3];

        OrderStatementLog orderStatementLog=new OrderStatementLog();
        orderStatementLog.setSuccess(!(state== OrderStatementStatusEnum.FAIL || state==OrderStatementStatusEnum.UNKNOWN));
        orderStatementLog.setCreateTime(LocalDateTime.now());
        orderStatementLog.setOps("尝试修改状态，从 "+getStateNameByState(orderStatement.getStatus())+" 修改为 "+ getStateNameByState(state));
        String result="修改状态成功";
        if(StringUtils.isNotEmpty(failReason))result+=" 支付失败原因："+failReason;
        if(price!=null)result+=" 退款金额："+price;
        orderStatementLog.setResult(result);
        orderStatementLog.setOrderStatementId(orderStatement.getId());
        orderStatementLogService.save(orderStatementLog);
        return joinPoint.proceed();
    }
}
